package com.example.myapplication.cp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;
import com.example.myapplication.databinding.ActivityContentProviderBinding;

import java.util.Random;

public class ContentProviderActivity extends AppCompatActivity {

    private ActivityContentProviderBinding binding;
    private MyContentObserver contentObserver = new MyContentObserver(new MyHandler());
    private ContentResolver contentResolver;


    @SuppressLint("Range")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    String id = binding.tvId.getText().toString();
                    Uri queryUri = Uri.parse("content://com.liaowei.cp.data/book/" + id);
                    Cursor cursor = queryBook(queryUri, contentResolver, "_id = ?", new String[]{id});
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            String name = cursor.getString(cursor.getColumnIndex("name"));
                            String category = cursor.getString(cursor.getColumnIndex("category"));
                            binding.tvId.setVisibility(View.VISIBLE);
                            binding.tvName.setText(name);
                            binding.tvCategory.setText(category);
                        }
                    }
                }
            }
        }
    }

    // 内容观察者，观察数据发生改变的时候会使用handler发送消息改变视图展示数据
    class MyContentObserver extends ContentObserver {
        private MyHandler handler;

        public MyContentObserver(MyHandler handler) {
            super(handler);
            this.handler = handler;
        }

        @Override
        public void onChange(boolean selfChange, @Nullable Uri uri) {
            super.onChange(selfChange, uri);
            this.handler.obtainMessage(1).sendToTarget();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityContentProviderBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        contentResolver = getContentResolver();
        // Uri uri = Uri.parse("content://com.liaowei.cp.data/book/1");
        // queryBook(uri, contentResolver, "_id = ?", new String[]{uri.getLastPathSegment()});

        Uri insertUri = Uri.parse("content://com.liaowei.cp.data/book");
        contentResolver.registerContentObserver(insertUri, true, contentObserver);

        Random random = new Random();
        binding.btnAdd.setOnClickListener(v -> {
            ContentValues cv = new ContentValues();
            cv.put("name", "书名" + random.nextInt(20));
            cv.put("category", "分类" + random.nextInt(5));
            long id = insertBook(insertUri, contentResolver, cv);
            binding.tvId.setText(String.valueOf(id));
            binding.tvId.setVisibility(View.INVISIBLE);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(contentObserver);
    }

    // 查询系统消息
    @SuppressLint("Range")
    private void querySystemSMS(ContentResolver contentResolver) {
        // 申请权限 在配置文件中写还有动态申请
        checkPermission(this);
        // 查询系统信息
        Uri msgUri = Uri.parse("content://sms/sent");
        Cursor c = contentResolver.query(msgUri, null, null, null, null);
        while (c.moveToNext()) {
            String msg = "";
            // 显示每条发信箱的内容
            // 遍历该行的列
            /*for (int i = 0; i < c.getColumnCount(); i++) {
                msg += c.getString(i) + " ";
            }*/
            // 如果只有拿接收者号码和信息内容
            // 系统指定的列名分别为 address body
             String address = c.getString(c.getColumnIndex("address"));
            String body = c.getString(c.getColumnIndex("body"));
            msg = address + " " + body;
            Log.e("ContentProviderActivity", "msg=" + msg);
        }
    }


    // 查询数据
    @SuppressLint("Range")
    public Cursor queryBook(Uri uri, ContentResolver contentResolver,String selection, String[] selectionArgs) {
        Cursor cursor = contentResolver.query(uri, null, selection, selectionArgs, null);
        // 返回游标时注意一定不能执行moveToNext方法，会将游标向下移动，如果只有一条数据，那么会移动到下一条数据，导致数据丢失
        /*if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex("_id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String category = cursor.getString(cursor.getColumnIndex("category"));
                Log.d("ContentProviderActivity", "book: id: " + id + " name: " + name + " category: " + category);
            }
        }*/
        return cursor;
    }

    // 插入数据
    public long insertBook(Uri uri, ContentResolver contentResolver, ContentValues values) {
        // ContentValues values = new ContentValues();
        // values.put("name", "水浒传");
        // values.put("category", "江湖");
        Uri returnUri = contentResolver.insert(uri, values);
        Log.i("Conernt", "insertBook: ");
        assert returnUri != null;
        long id = ContentUris.parseId(returnUri);
        Toast.makeText(this, "插入成功，id为：" + id, Toast.LENGTH_SHORT).show();
        return id;
    }

    private void checkPermission(Activity activity) {
        // Storage Permissions
        final int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_SMS,
        };
        try {
            // 检测是否有读短信箱的权限
            int permission = ActivityCompat.checkSelfPermission(ContentProviderActivity.this,
                    "android.permission.READ_SMS");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有读短信箱的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(ContentProviderActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}